const { mysql } = require('../qcloud')

module.exports = async ctx => {
  const { page, openid } = ctx.request.query
  const size = 10

  const mysqlSelect = mysql('books')
    .select('books.*', 'cSessionInfo.user_info')
    .join('cSessionInfo', 'books.openid', 'cSessionInfo.open_id')
    .orderBy('books.id', 'desc')
  // .limit(size)
  // .offset(page * size)
  //join 限制的条件 limit 返回多少条数据 offset从第几条开始
  let books
  if (openid) {
    books = await mysqlSelect.where('books.openid', openid)
  } else {
    books = await mysqlSelect.limit(size).offset(page * size)
  }
  ctx.state.data = {
    msg: books.map(v => {
      let userInfo = JSON.parse(v.user_info)
      return Object.assign({}, v, {
        user_info: {
          nickname: userInfo.nickName
        }
      })
    })
  }
}
